function [ EC ] = APEbatchloadsif( PathName, savetype )
% [ EC ] = APEbatchloadsif( savetype )
%
% Script to batch-convert all .sif files in one folder to APE-.mat format
% as well as to CSV or Excel. If no options are given, a interactive
% session will be used.
%
% INPUT     PathName    :   path to the .sif files to be processed
%           savetype    :   0 = only .mat
%                           1 = .mat & CSV
%                           2 = .mat & Excel (.xls)
%
% OUTPUT    EC          :   error code (0 = success, 1 = error)
%

%  (c) F. Dworkowski, 2011-2014
%      Version 1.1, 2014-01-27

%% BATCH SIF READER

%% Config
% savetypepreset = 0;                % Config save type
logfilename = ['log-APEbatchloadsif_',date,'.txt'];
EC = 0;
oldpath=cd;

%% check for input argument
% if nargin==0
%     savetype = savetypepreset;
% end
    
if nargin>2,
    help APEbatchloadsif
    EC = 1;
    return
end

if nargin==0 || nargin==1 || (savetype>2)
    answer=questdlg({'Do you want to save additional file types?'...
        '' '' 'XLS : Excel file' '' ...
        'CSV : Text file, CSV type' '       (Att: can take a LONG time!!)' ...
        '' 'No  : Only convert from .sif to APE-type .mat' '' ''},...
        'Choose additional types',...
        'XLS','CSV','No','No');
    switch answer
        case 'XLS'
            savetype = 2;
        case 'CSV'
            savetype = 1;
        case 'No'
            savetype = 0;
    end
end
        
%% Choose Folder and detect files

if nargin == 0 || (~ischar(PathName) && PathName>0)
    [FileName,PathName,FilterIndex] = uigetfile('*.sif');
    if isequal(FileName,0)
       disp('User selected Cancel')
       EC = 1;
       return
    else
       disp(['User selected ', fullfile(PathName, FileName)])
    end
end

if ischar(PathName) && ~isempty(PathName)
    cd(PathName)
end

filelist=dir('*.sif');      % Detect all available .sif files
% Initialize Logfile
logfilename = fullfile(cd,logfilename);
diary(logfilename)
disp(' ')
disp('=========== SLS APE .sif Batch Converter ===========')
disp(['===========     ',datestr(now),'     ==========='])
disp(' ')
diary off                   % Switch logging of prior to loadsif

%% Conversion Loop
for i = 1:length(filelist)  % Do for all detected .sif files
    [pathstr, datasetname, ext] = fileparts(filelist(i).name);
   [rc] = loadsif_nonGUI(datasetname, 1);   % convert sif to mat
   diary on                 % switch logging on. Should be off for 
                            % loadsif due to the unavoidable output there
   if rc == 0
       disp(['File ',(filelist(i).name),' saved'])      % LOG output
   else
       disp(['Saveing of  ',(filelist(i).name),' FAILED!']) % LOG Output
       errordlg('Save failed!!')
       EC = 1;
       cd(oldpath);            % go back to old path
       return
   end
   
   switch savetype 
       case 1   % save as ASCII
           load(datasetname, '-mat')
           
%% CSV save           
       datacsv=zeros(size(datay,2),(size(datay,1)+1));   
       datacsv=[datax.', datay.'];
       csvwrite([datasetname,'.csv'],datacsv);
           
%% line-by-line save
%            h = waitbar(100,{'Please wait...' 'gathering info...'},...
%             'Name','Saving *.csv...');    % Status Bar INIT
%            for j = 1:length(datay(1,:))
%                M = [datax(1,j); datay(:,j)];
%                dlmwrite([datasetname,'.csv'], M, 'delimiter', '\t', ...
%                 'precision', 6, '-append')
%                 state=((j/length(datay(1,:)))+0.1);
%                 waitbar(state,h);
%            end
%           close(h);

%% Classical Save
%            datax=datax';
%            datayy=datay';
%            d = [datax datayy];
%            save([datasetname,'.csv'], 'd', '-ascii')

           disp(['File ',datasetname,'.csv saved.'])      % LOG output

%% XLS save
       case 2   % save as XLS
           load(datasetname, '-mat')
           d = {'datax','datay'};
           datax=datax';
           datay=datay';
           [status,msginfo] = xlswrite([datasetname,'.xls'], d, 1, 'A1');
           if status == 0
               errortxt = {['XLS file ',datasetname,...
                   ' could not be saved successfully!'] '' '' ...
                   char(struct2cell(msginfo))};
               disp(char(errortxt));
               errordlg(errortxt);
               EC = 1;
           else
               disp(['Headers in file ',datasetname,'.xls saved successfully.']);
           end
           [status,msginfo] = xlswrite([datasetname,'.xls'], datax, 1, 'A2');
           if status == 0
               errortxt = {['XLS file ',datasetname,...
                   ' could not be saved successfully!'] '' '' ...
                   char(struct2cell(msginfo))};
               disp(char(errortxt));
               errordlg(errortxt);
               EC = 1;
           else
               disp(['Datax in file ',datasetname,'.xls saved successfully.']);
           end
           [status,msginfo] = xlswrite([datasetname,'.xls'], datay, 1, 'B2');
           if status == 0
               errortxt = {['XLS file ',datasetname,...
                   ' could not be saved successfully!'] '' '' ...
                   char(struct2cell(msginfo))};
               disp(char(errortxt));
               errordlg(errortxt);
               EC = 1;
           else
               disp(['File ',datasetname,'.xls saved successfully.']);
           end
           footerXLS(:,1)=fieldnames(footer);
           footerXLS(:,2)=struct2cell(footer);
           [status,msginfo] = xlswrite([datasetname,'.xls'], footerXLS, 2, 'A1');
           if status == 0
               errortxt = {['XLS file ',datasetname,...
                   ' could not be saved successfully!'] '' '' ...
                   char(struct2cell(msginfo))};
               disp(errortxt);
               errordlg(errortxt);
               EC = 1;
           else
               disp(['File ',datasetname,'.xls saved successfully.']);
           end
   end
   diary off            % switch logging of prior to next loadsif in loop
end
cd(oldpath);            % go back to old path
diary off;              % suspend logging
end

